﻿using eslib.tools.config;

namespace eslib.FileManageLib
{
    /// <summary>
    /// 文件
    /// </summary>
    public class FileItem : FileBase
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="name">文件名</param>
        /// <param name="dir">所属目录</param>
        public FileItem(string name, Dir dir) : base(name, dir)
        {
        }


        public string GetText()
            => File.ReadAllText(FilePath);

        public void SetText(string text)
            => File.WriteAllText(FilePath, text);

        public byte[] GetBuffer()
            => File.ReadAllBytes(FilePath);

        public void SetBuffer(byte[] buf)
            => File.WriteAllBytes(FilePath, buf);

        public FileInfo GetFileInfo()
        {
            return new FileInfo(FilePath);
        }


        /// <summary>
        /// 加载对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public T LoadObject<T>() where T : new()
        {
            return GenericJsonConfig.LoadFromString<T>(GetText());
        }

        /// <summary>
        /// 保存对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        public void SaveObject<T>(T obj) where T : new()
        {
            string json = GenericJsonConfig.Save(obj);
            SetText(json);
        }


        public override void Delete()
        {
            File.Delete(FilePath);
        }

        /// <summary>
        /// 移动到dir
        /// </summary>
        /// <param name="target"></param>
        public override FileBase MoveTo(Dir target)
        {
            string oldfile = FilePath;

            ((Dir)this.Parent).RemoveChild(this);

            target.AddChild(this);
            this.Parent = target;

            string newfile = FilePath;

            //复制
            File.Copy(oldfile, newfile, true);
            //删除
            File.Delete(oldfile);

            return this;
        }

        /// <summary>
        /// 复制到dir
        /// </summary>
        /// <param name="target"></param>
        public override FileBase CopyTo(Dir target)
        {
            FileItem newItem = new FileItem(this.Name, target);
            target.AddChild(newItem);

            //复制
            File.Copy(this.FilePath, newItem.FilePath);

            return this;
        }


        public override void ReName(string name)
        {
            string dir = Path.GetDirectoryName(FilePath);
            string newname = Path.Combine(dir, name);
            File.Move(FilePath, newname);

            this.Name = name;
        }
    }
}